package com.android.webttest.View;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.lifecycle.ViewModelProvider;
import com.android.webttest.R;
import com.android.webttest.ViewModel.MainViewModel;
import com.android.webttest.service.GoodSyncService;
import com.android.webttest.utils.StatusBarUtil;
import com.android.webttest.utils.TokenManager;
import com.android.webttest.utils.Tools;
import com.google.android.material.textfield.TextInputEditText;
import android.text.Editable;
import android.text.TextWatcher;

import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private MainViewModel viewModel;
    private ImageView captchaImageView;
    private Button loginEntryBtn;
    private TextInputEditText loginAccount;
    private TextInputEditText loginPassword;
    private TextInputEditText loginVerify;

    private CheckBox rememberPasswordCheckbox;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化 TokenManager
        try {
            TokenManager.init(this);
        } catch (Exception e) {
            e.printStackTrace();
            Tools.Toast(MainActivity.this, "初始化 TokenManager 失败");
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1);
        }
        // 使用工具类设置状态栏
        StatusBarUtil.setImmersiveStatusBarR(this);

        // 初始化控件
        captchaImageView = findViewById(R.id.captchaImageView);
        loginEntryBtn = findViewById(R.id.login_entry_btn);
        loginAccount = findViewById(R.id.login_account);
        loginPassword = findViewById(R.id.login_password);
        loginVerify = findViewById(R.id.login_verify);
        rememberPasswordCheckbox =  findViewById(R.id.remember_password_checkbox);
        sharedPreferences = getSharedPreferences("LoginPrefs", MODE_PRIVATE);
        // 读取保存的账号和密码
        String savedAccount = sharedPreferences.getString("account", "");
        String savedPassword = sharedPreferences.getString("password", "");
        boolean isRemembered = sharedPreferences.getBoolean("remember", false);
        if (isRemembered) {
            loginAccount.setText(savedAccount);
            loginPassword.setText(savedPassword);
            rememberPasswordCheckbox.setChecked(true);
        }

        // 初始化 ViewModel
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);

        // 观察验证码图片的变化
        viewModel.getCaptchaImage().observe(this, bitmap -> captchaImageView.setImageBitmap(bitmap));

        // 观察 toast 消息的变化
        viewModel.getToastMessage().observe(this, message -> Tools.Toast(MainActivity.this, message));

        // 观察认证 token 的变化
        viewModel.getAuthToken().observe(this, token -> {
            if (token != null) {
                try {
                    // 将 token 存储到本地
                    TokenManager.encryptAndStoreToken(MainActivity.this, token);
                    //获取User
                    viewModel.getUserInfo();
                    // 启动 UserManageLayout 并销毁 MainActivity
                    Intent intent = new Intent(MainActivity.this, UserManageLayout.class);
                    //Service启动
                    Intent serviceIntent = new Intent(this, GoodSyncService.class);
                    startService(serviceIntent);
                    startActivity(intent);
                    finish();//销毁界面
                } catch (Exception e) {
                    e.printStackTrace();
                    Tools.Toast(MainActivity.this, "存储 token 失败");
                }
            }
        });

        // 获取验证码图片
        viewModel.getCheckcodeImage();
        captchaImageView.setOnClickListener(v -> viewModel.getCheckcodeImage());

        // 登录按钮逻辑
        loginEntryBtn.setOnClickListener(v -> {
            String account = Objects.requireNonNull(loginAccount.getText()).toString();
            String password = Objects.requireNonNull(loginPassword.getText()).toString();
            String verify = Objects.requireNonNull(loginVerify.getText()).toString();

            if (account.isEmpty()) {
                Tools.Toast(MainActivity.this, "请输入账号!");
                return;
            }
            if (password.isEmpty()) {
                Tools.Toast(MainActivity.this, "请输入密码!");
                return;
            }
            if (verify.isEmpty()) {
                Tools.Toast(MainActivity.this, "请输入验证码!");
                return;
            }

            // 保存账号和密码
            SharedPreferences.Editor editor = sharedPreferences.edit();
            if (rememberPasswordCheckbox.isChecked()) {
                editor.putString("account", account);
                editor.putString("password", password);
                editor.putBoolean("remember", true);
            } else {
                editor.remove("account");
                editor.remove("password");
                editor.putBoolean("remember", false);
            }
            editor.apply();
            viewModel.verifyLogin(account, password, verify);
        });

        // 添加 TextWatcher 到 loginVerify
        loginVerify.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要实现
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4) {
                    hideKeyboard();
                }
            }
        });
    }

    // 关闭软键盘的方法
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null && getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}
